package invertedindex;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;

public class Search {

	public SortedMap<Integer, Integer> query(String keyword) {
		SortedMap<Integer, String> resultInHex = new TreeMap<Integer, String> ();

		try {
			DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

			Connection conn = DriverManager.getConnection(
					"jdbc:oracle:thin:@localhost:1521:TEACH", "wunan",
					"uviccsc");

			PreparedStatement stmt = conn
					.prepareStatement("SELECT firstdoc, block from postings WHERE word=?");

			stmt.setString(1, keyword);

			ResultSet rset = stmt.executeQuery();

			while (rset.next()) {
				resultInHex.put(rset.getInt("firstdoc"), rset.getString("block"));

				//System.out.println("firstdoc: " + rset.getString("firstdoc"));
				//System.out.println("blcok: " + rset.getString("block"));
			}
		} catch (SQLException e) {
			System.out.println(e);
		}
		
		return constructResult(resultInHex);
	}

	private SortedMap<Integer, Integer> constructResult(SortedMap<Integer, String> resultInHex) {
		
		SortedMap<Integer, Integer> resultList = Encoding.Strings2Map(resultInHex);
		
		Iterator<Integer> i = resultList.keySet().iterator();
		
		System.out.println("Total Match document: " + resultList.size());
		while (i.hasNext()) {
			int docID = i.next();
			int count = resultList.get(docID);
			System.out.println("Document ID: " + docID + " Count: " + count);
		}
		
		return resultList;
	}

	public static void main(String[] args) {
		Search search = new Search();
		search.query("acquire");
	}
}
